package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "用户接口")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final IUserService userService;

    @ApiOperation("新增用户")
    @PostMapping
    public void add(@RequestBody UserFormDTO dto) {
        User user = new User();
        BeanUtil.copyProperties(dto, user);
        userService.save(user);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        userService.removeById(id);
    }

    @ApiOperation("查询用户和地址")
    @GetMapping("/{id}")
    public UserVO getUser(@PathVariable Long id) {
//        User user = userService.getById(id);
//        UserVO userVO = new UserVO();
//        BeanUtil.copyProperties(user, userVO);
       UserVO userVO = userService.queryUserAndAddressById(id);
        return userVO;
    }

    @ApiOperation("根据id批量查询用户和地址")
    @GetMapping
    public List<UserVO> getUserByIds(@RequestParam("ids") List<Long> ids) {
/*        List<User> users = userService.listByIds(ids);
        *//*
        List<UserVO> voes = new ArrayList<>();
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            voes.add(userVO);
        }
        return voes;*//*
        List<UserVO> userVOS = BeanUtil.copyToList(users, UserVO.class);*/
        List<UserVO> userVOS = userService.queryUserAndAddressByIds(ids);
        return userVOS;
    }

    @ApiOperation("根据id扣减余额")
    @PutMapping("/{id}/deduction/{amount}")
    public void deduct(@PathVariable("id") Long id, @PathVariable("amount") Integer amount){
        userService.deduct(id,amount);
    }

    @ApiOperation("根据复杂条件查询用户")
    @PostMapping("/list")
    public List<UserVO> list(@RequestBody UserQuery userQuery){
        List<UserVO> list =  userService.getList(userQuery);
        return list;
    }
}
